<template>
    <div v-observe-visibility="{callback: visibilityChanged, throttle: 300,}">
        <th-main-page title="${classInfo.className?uncap_first}">
            <th-page-section>
                <el-row class="margin-b5">
                    <el-col>
                        <el-input size="mini" v-model="filters.keyword" placeholder="关键字" style="width:300px;" @keyup.native.enter="reloadData" />
                        <el-button size="mini" icon="el-icon-refresh" @click="reloadData" style="margin-left:5px;">查询</el-button>
                    </el-col>
                </el-row>

                <el-row class="panel-content">
                    <el-row>
                        <!--列表 sortable="custom"-->
                        <el-table highlight-current-row class="th-el-table" header-row-class-name="hr-table-header" size="mini"
                                  ref="dataTable" v-loading="onLoading"   @sort-change="onSortChange"
                                  :data="dataList">
                <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0>
                    <#list classInfo.fieldList as fieldItem >
                        <#if fieldItem.fieldName != "id" && fieldItem.fieldName != "orderIndex">
                            <el-table-column
                                    prop="${fieldItem.fieldName}"
                                    header-align="center"
                                    align="center"
                                    label="${fieldItem.fieldComment}" show-overflow-tooltip>
                            </el-table-column>
                        </#if>
                    </#list>
                </#if>
                            <el-table-column label="操作" width="120" align="center" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <el-tooltip effect="dark" content="编辑" placement="top" :open-delay="500">
                                        <i class="iconfont icon-bianji1" style="cursor: pointer;font-size: 14px;"
                                           @click.stop.prevent="handleUpdate(scope.row)"></i>
                                    </el-tooltip>
                                    <el-tooltip effect="dark" content="复制" placement="top" :open-delay="500">
                                        <i class="iconfont icon-copy" style="font-size:20px;cursor: pointer;margin-left:5px;" @click.stop.prevent="handleUpdate(scope.row, true)"></i>
                                    </el-tooltip>
                                    <el-tooltip effect="dark" content="删除" placement="top" :open-delay="500">
                                        <i class="iconfont icon-shanchu2" style="cursor: pointer;margin-left:5px;font-size: 14px;"
                                           @click.stop.prevent="handleDelete(scope.row)"></i>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>

                    <el-row v-show="true" class="margin-t5">
                        <el-col :span="12">
                            <el-button size="mini" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                            <el-button type="primary" size="mini" @click="exportTableData" :loading="exporting">导出</el-button>
                        </el-col>
                        <el-col :span="12" align="right">
                            <el-pagination layout="sizes, prev, pager, next" size="mini" :page-size="filters.pageSize" :current-page="page"
                                           :page-sizes="[5, 10, 15, 20, 30, 50, 100, 300, 500]" :total="total"
                                           @current-change="onPaginationChange" @size-change="onPaginationSizeChange"></el-pagination>
                        </el-col>
                    </el-row>

                </el-row>
            </th-page-section>
        </th-main-page>

<!--    <update :formVisible.sync="updateDialogVisible" :id="toOperateId" :isCloneOperation="isCloneOperation" @afterUpdate="loadData" @afterCreate="afterCreate"></update>-->
    </div>
</template>

<script>
    // import update from './update'
    import util from "@/common/js/util";

    export default {
        // components: {update},

        data() {
            return {
                cacheKey: 'TODO-${classInfo.className?uncap_first}.mgmt.filter',
                updateDialogVisible: false,
                toOperateId: null,
                filters: {
                    keyword: null,
                    pageSize: 20,
                    sortField: null,
                    sortDirection: null,
                },
                dataList: [],
                // pagination
                page: 1,
                total: 0,
                onLoading: false,
                exporting: false,

                isCloneOperation: false,
            }
        },

        methods: {
            afterCreate(id) {
                // console.log('afterCreate id:', id)
                this.toOperateId = id
                this.isCloneOperation = false
            },
            visibilityChanged (isVisible, entry) {
                if (isVisible) {
                    this.$nextTick(() => {
                        if (this.$refs.dataTable) {
                            this.$refs.dataTable.doLayout();
                        }
                    });
                }
            },
            onSortChange(sortParam) {
                this.page = 1
                const {column, prop, order} = sortParam
                this.filters.sortDirection = null
                this.filters.sortField = null
                if (order != null) {
                    this.filters.sortDirection = (order == 'ascending') ? 'ASC' : 'DESC'
                    this.filters.sortField = prop
                }
                this.reloadData()
            },
            handleAdd() {
                this.toOperateId = null
                this.updateDialogVisible = true
                this.isCloneOperation = false
            },
            handleUpdate(row, isCloneOperation) {
                this.toOperateId = row.id
                this.updateDialogVisible = true
                this.isCloneOperation = isCloneOperation
            },
            async handleDelete(row) {
                this.$confirm('确认要删除该记录（' + row.name + '）吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.delete(row)
                })
            },
            async delete(row) {
                this.$set(row, "deleting", true)
                let response = await this.$todoService.delete(row.id)
                this.$set(row, "deleting", false)
                if (response.errorNo == 0) {
                    this.$message.success("操作成功")
                    await this.loadData()
                } else {
                    this.$message.error('操作失败')
                }
            },
            async reloadData() {
                this.page = 1
                await this.loadData()
            },
            async loadData() {
                let cacheSeconds = 24 * 60 * 60 * 1000 // keep 24 hours
                this.$localStorage.set(this.cacheKey, this.filters, cacheSeconds)

                let param = {
                    keyword: this.filters.keyword,
                    page: this.page - 1,
                    size: this.filters.pageSize,
                    sortField: this.filters.sortField,
                    sortDirection: this.filters.sortDirection,
                };

                this.onLoading = true
                let dataList = []
                let total = 0
                let data = await this.$todoService.list(param)
                if (data && data.result) {
                    dataList = data.result.content
                    total = data.result.totalElements
                }
                this.dataList = dataList
                this.total = total
                this.onLoading = false
            },
            async exportTableData() {
                this.exporting = true
                let param = {
                    keyword: this.filters.keyword,
                    page: 0,
                    size: 999999,
                    sortField: this.filters.sortField,
                    sortDirection: this.filters.sortDirection,
                }
                let response = await this.$todoService.export(param)
                // console.log('response:', response)
                let result = response.result
                let byteData = util.stringToArrayBuffer(atob(result.fileContent))
                let blob = new Blob([byteData], {type: "application/octet-binary"})
                let link = document.createElement('a')
                link.href = window.URL.createObjectURL(blob)
                link.download = result.fileName
                link.click()
                this.exporting = false
            },
            onPaginationSizeChange(val) {
                this.page = 1
                this.filters.pageSize = val
                this.loadData()
            },

            onPaginationChange(val) {
                this.page = val;
                this.loadData()
            },
        },

        computed: {
        },

        mounted() {
            let filterStorage = this.$localStorage.get(this.cacheKey)
            if (filterStorage) {
                this.filters = filterStorage
            }
            this.loadData()
        }
    }
</script>

<style lang="scss">

</style>
